﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseUserTest.DB
{
    public class DBOrder
    {
        static DatabaseUserTest.DatabaseContext db = new DatabaseUserTest.DatabaseContext();
        
        // Finds order by phone number
        public Order FindOrder(int phoneNo)
        {
            var query = from o in db.Orders select o;
            
            foreach (Order item in query)
            {
                if (item.User.PhoneNo == phoneNo)
                {
                    return item;
                }
            }
            return null;
        }

        // Finds order by email
        public Order FindOrder(string email)
        {
            var query = from o in db.Orders select o;
            
            foreach (Order item in query)
            {
                if (item.User.Mail == email)
                {
                    return item;
                }
            }
            return null;
        }

        public void AddOrder(Order order)
        {
            db.Orders.Add(order);
            db.SaveChanges();
        }

        // Deletes orders more than 7 days older than the arrival date of the plane
        public void DeleteOrders()
        {
            IQueryable<Order> query = from o in db.Orders select o;
            
            foreach (Order item in query)
            {
                if (item.Plane.Arrival < DateTime.Now.AddDays(-7))
                {
                    db.Orders.Remove(item);
                }
            }
        }
    }
}
